package org.byd.dmsja.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import org.byd.dmsja.entity.DmsUserDb;
import org.byd.dmsja.service.DmsUserService;


import java.util.Calendar;
import java.util.Map;


public class JWTUtils {
    private static String SECRET = "swdtoken!Q@W#E$R";

    /**
     * 生产token
     */
    public static String genToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 3600); //默认7天过期

        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
        String token = builder.sign(Algorithm.HMAC256(SECRET));//签名
        return token;
    }

    /**
     * 验证token
     */
    public static DecodedJWT verify(String token) {
        //如果有任何验证异常，此处都会抛出异常
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT;
    }

    /**
     * 获取token中的 payload
     */
    public static DecodedJWT getToken(String token) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT;
    }

    public static DmsUserDb getLoginUser(HttpServletRequest request, DmsUserService dmsUserService) {
        try {
            var tokenText = request.getHeader("token");
            var tokenEx = getToken(tokenText);
            var userId = tokenEx.getClaim("user_id").asString();
            return dmsUserService.findUserByUserId(userId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
